package frame.service.standard.impl;

import frame.service.context.ServiceContext;
import frame.service.standard.Constants;
import frame.service.standard.MiayFilter;
import frame.service.standard.MiayRuntimeException;
import frame.service.util.FrameUtil;
import http.RedisSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 防重放设计
 * */
public class LimitReplayFilter implements MiayFilter {
    @Override
    public void doPass(ServiceContext context) {
        String replayId = context.getReqContentString(Constants.REQUEST_REPLAY_ID);
        if(replayId==null){
            throw new MiayRuntimeException("920006", new String[]{Constants.REQUEST_REPLAY_ID});
        }
        if(context.getRedisSession().getSessionData(RedisSession.Constants.REQUEST_LIMIT_REPLAY)==null){
            List<String> limits = new ArrayList<String>();
            limits.add(replayId);
            context.getRedisSession().setSessionData(
                    RedisSession.Constants.REQUEST_LIMIT_REPLAY,
                    FrameUtil.obj2json(limits)
            );
        }else{
            List<String> limits = context.getRedisSession().getSessionData(RedisSession.Constants.REQUEST_LIMIT_REPLAY, List.class);
            if(limits.contains(replayId)){
                throw new MiayRuntimeException("930009");
            }else{
                limits.add(replayId);
                context.getRedisSession().setSessionData(
                        RedisSession.Constants.REQUEST_LIMIT_REPLAY,
                        FrameUtil.obj2json(limits)
                );
            }
        }
    }

    /**
     * 安全接口增加授权设置
     * */
    @Override
    public boolean checkSuit(ServiceContext context) {
        String safeMode = context.getReqContentString(Constants.REQUEST_SAFE_MODE);
        return Constants.SAFE_MODE_SECURE.equals(safeMode);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
